var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var request = require('request ');
var path= require('path');

var app = express();
app.use(bodyParser.json());

app.use('/urlDownLoadFile', (req, res) => {
  var filePaths = req.body.filepaths,
    dirPath = req.body.dirPath;
  var fileDirPath = path.join(__dirname, './static/', dirPath);
  if (!fs.existsSync(fileDirPath)) {
    fs.mkdirSync(fileDirPath);
  }
  filePaths.forEach(item => {
    if (item !== '') {
      var lastIndex = item.lastIndexOf('/'),
        fileName = item.substr(lastIndex + 1);
      var stream = fs.createWriteStream(path.join(fileDirPath, fileName));
      request(item).pipe(stream).on('close', (err) => {
        if (err) {
          console.log(err);
        }
      });
    }
  });
  res.send('');
});

app.use('/', express.static('./static'));
app.listen(3000);
